<?php

namespace App\Logic;

use App\Model\EmailLog;
use App\Model\EmailTemplate;
use Exception;

class AdminEmailLogic
{
    /**
     * 模板列表
     * @return array
     */
    public static function listTemplate(): array
    {
        return [
            'total' => EmailTemplate::query()->count(),
            'pages' => 1,
            'records' => EmailTemplate::query()->orderBy('id')->get()->toArray()
        ];
    }

    /**
     * 修改模板
     * @param $id
     * @param $input
     * @return true
     * @throws Exception
     */
    public static function editTemplate($id, $input): true
    {
        $template = EmailTemplate::query()->where('id', $id)->first();
        if (!$template) {
            throw new Exception('模板不存在');
        }
        EmailTemplate::query()->where('id', $id)->update([
            'title' => $input['title'] ?? $template['title'],
            'content' => $input['content'],
            'params' => $input['params'],
        ]);
        return true;
    }

    /**
     * 邮件日志
     * @param $input
     * @return array
     */
    public static function sendLog($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = EmailLog::query()->when(!empty($input['query']['email']), function ($q) use ($input) {
            $q->where('email', $input['query']['email']);
        });
        $total = $query->count();
        if ($total) {
            $records = $query->orderBy('id', 'desc')->offset($offset)->limit($pageSize)->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }
}